package com.zhouyu.mysql;

import com.zhouyu.mysql.core.*;
import com.zhouyu.mysql.dict.DictTable;
import com.zhouyu.mysql.dict.SystemDict;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.alter.Alter;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.FromItemVisitorAdapter;
import net.sf.jsqlparser.statement.select.PlainSelect;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.zhouyu.mysql.page.IndexPage.PAGE_NEW_INFIMUM;

/**
 * 大都督周瑜（我的微信: dadudu6789）
 */
public class SqlExecutor {

    private HaInnodb haInnodb = new HaInnodb();

    public void createTable(CreateTable createTableStatement) {
        haInnodb.createTable(createTableStatement);
    }

    public void insert(Insert insertStatement) {
        haInnodb.insert(insertStatement);
    }

    public String select(PlainSelect plainSelectStatement) {

        // 获取表名
        final String[] tableNameArray = new String[1];
        plainSelectStatement.getFromItem().accept(new FromItemVisitorAdapter() {
            @Override
            public void visit(Table table) {
                tableNameArray[0] = table.getName();
            }
        });
        String tableName = tableNameArray[0];

        DictTable dictTable = SystemDict.getInstance().getNameTables().get(tableName);

        DTuple dTuple = DTupleUtil.convert(plainSelectStatement);

        PageCur pageCur = new PageCur();
        // 取当前表对应的B+树的最左边叶子节点
        pageCur.setPageNo(BtrUtil.getFirstLeafPage(dictTable).fil_page_get_page_offset());
        pageCur.setRec(PAGE_NEW_INFIMUM);

        List<HashMap<String, Object>> result = new ArrayList<>();

        while (true) {
            SelectOneResult selectOneResult = haInnodb.select_one(dictTable, pageCur, dTuple);
            boolean endOfIndex = selectOneResult.isEndOfIndex();

            if (endOfIndex) {
                break;
            }

            HashMap<String, Object> recContent = selectOneResult.getRecContent();
            result.add(recContent);

            pageCur = selectOneResult.getPageCur();
        }

        return result.toString();
    }

    public void alter(Alter alterStatement) {
        haInnodb.alter(alterStatement);
    }
}
